package com.dap.cms.governance.controller;


import com.dap.cms.governance.common.RequestHolder;
import com.dap.cms.governance.po.CmsManagerPo;
import com.dap.cms.governance.po.CmsMessagePo;
import com.dap.cms.governance.service.CmsManagerService;
import com.dap.cms.governance.service.CmsMessageService;
import com.dap.dao.model.Order;
import com.dap.dao.model.QueryResult;
import com.fesine.commons.entity.Result;
import com.fesine.commons.enums.ResultEnum;
import com.fesine.commons.util.ResultUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description: 项目管理类
 * @author: tiger
 * @createTime:2018/6/12
 * @update:修改内容
 * @author: tiger
 * @updateTime:2018/6/12
 */
@Api(value = "/v1", description = "消息类接口")
@RestController
@RequestMapping("/v1")
public class CmsMessageController {
    private static final Logger logger = LoggerFactory.getLogger(CmsMessageController.class);
    @Autowired
    private CmsMessageService cmsMessageService;
    @Autowired
    private CmsManagerService cmsManagerService;

    /**
     * 获取消息列表
     *
     * @param readFlag
     * @param pageIndex
     * @param pageSize
     * @return
     */
    @ApiOperation(value = "获取当前用户消息列表", httpMethod = "GET")
    @GetMapping("/msgs")
    public Result getMessages(@RequestParam(required = false, defaultValue = "0") Integer readFlag,
                              @RequestParam(required = false, defaultValue = "1") Integer pageIndex,
                              @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
        CmsMessagePo CmsMessagePo = new CmsMessagePo();
        CmsMessagePo.setToUserId(RequestHolder.getCurrentUser().getId());
        CmsMessagePo.setReadFlag(readFlag);
        CmsMessagePo.addOrder(Order.desc("send_time"));
        QueryResult<CmsMessagePo> CmsMessagePoQueryResult = cmsMessageService.listPage(CmsMessagePo,
                pageIndex, pageSize);
        Map<String, Object> map = new HashMap<>();
        List<CmsMessagePo> CmsMessagePos = CmsMessagePoQueryResult.getResultlist();
        List<CmsMessagePo> vos = new ArrayList<>();
        for (CmsMessagePo po : CmsMessagePos) {
            CmsMessagePo cmsMessageVo = new CmsMessagePo();
            BeanUtils.copyProperties(po, cmsMessageVo);
            CmsManagerPo cmsManagerPo = new CmsManagerPo();
            cmsManagerPo.setId(po.getFromUserId());
            cmsManagerPo = cmsManagerService.get(cmsManagerPo);
            if (null != cmsManagerPo) {
                cmsMessageVo.setFromUserName(cmsManagerPo.getUsername());
            }
            vos.add(cmsMessageVo);
        }
        long totalRecord = CmsMessagePoQueryResult.getTotalrecord();
        if (null != CmsMessagePos && !CmsMessagePos.isEmpty()) {
            map.put("totalRecord", totalRecord);
            map.put("resultList", vos);
        }
        return ResultUtils.success(map);
    }

    /**
     * 将消息标记为已读
     *
     * @param ids
     * @return
     */
    @ApiOperation(value = "将消息标记为已读(批量)", httpMethod = "PUT")
    @PutMapping("/msgs/{ids}")
    public Result changeFlag(@PathVariable String ids) {
        try {
            cmsMessageService.changeFlag(ids);
            return ResultUtils.success(ResultEnum.CREATED, null);
        } catch (Exception e) {
            logger.error("服务器错误", e);
            return ResultUtils.error(500, "服务器发生错误");
        }
    }

    /**
     * 将消息标记为未读
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "将消息标记为未读", httpMethod = "PUT")
    @PutMapping("/msg/{id}")
    public Result changeFlag(@PathVariable Integer id) {
        try {
            CmsMessagePo msgPo = new CmsMessagePo();
            msgPo.setId(id);
            msgPo.setReadFlag(0);
            cmsMessageService.update(msgPo);
            return ResultUtils.success(ResultEnum.CREATED, null);
        } catch (Exception e) {
            logger.error("服务器错误", e);
            return ResultUtils.error(500, "服务器发生错误");
        }
    }

    /**
     * 批量删除消息
     *
     * @param ids
     * @return
     */
    @ApiOperation(value = "删除消息(支持批量)", httpMethod = "DELETE")
    @DeleteMapping("/msg/{ids}")
    public Result deleteMsg(@PathVariable String ids) {
        try {
            cmsMessageService.deleteMsg(ids);
            return ResultUtils.success(ResultEnum.DELETED, null);
        } catch (Exception e) {
            logger.error("服务器错误", e);
            return ResultUtils.error(500, "服务器发生错误");
        }
    }
}